package com.zhuxulin.tab.threads;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.NoSuchElementException;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;

import com.zhuxulin.tab.App;
import com.zhuxulin.tab.bluetooth.SendMessage;
import com.zhuxulin.tab.utils.LogUtils;

public class SocketConnect extends Thread implements Runnable {
	private static final String TAG = SocketConnect.class.getSimpleName();
	private BluetoothAdapter adapter = null;
	private BluetoothDevice device = null;
	private BluetoothSocket socket = null;
	// 00001101-0000-1000-8000-00805F9B34FB
	//
	// 00001108-0000-1000-8000-00805F9B34FB
	//
	// 0000110B-0000-1000-8000-00805F9B34FB
	//
	// 0000110E-0000-1000-8000-00805F9B34FB
	//
	// 0000111E-0000-1000-8000-00805F9B34FB
	private UUID id = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	// private BluetoothSocket socket=null;
	// private Handler handler=null;
	private App app = null;
	private Context context = null;

	// public SocketConnect(App app, Handler handler) {
	// this.socket=socket;
	// this.app=app;
	// this.handler=handler;
	// }

	public SocketConnect(App app, Context context) {
		this.app = app;
		this.context = context;
	}
	private void checkEnvirment(){
		adapter=(adapter==null?BluetoothAdapter.getDefaultAdapter():this.adapter);
		device=(device==null?getBluetoothDevice():this.device);
		socket=(socket==null?createBluetoothSocket(device):this.socket);
		
	}
	@Override
	public void run() {
		LogUtils.i(TAG, "Thread start!");
		// Message msg=new Message();
		LogUtils.i(TAG, "Begin get adapter!");
		adapter = BluetoothAdapter.getDefaultAdapter();
		LogUtils.i(TAG, "End get adapter!adapter:" + adapter);
		LogUtils.i(TAG, "Begin get device!");
		device = getBluetoothDevice();
		LogUtils.i(TAG, "End get device!devece:" + device);
		LogUtils.i(TAG, "Begin create socket!");
		socket = createBluetoothSocket(device);
		LogUtils.i(TAG, "End create socket!socket:" + socket);
		app.setAdapter(adapter);
		app.setDevice(device);
		app.setSocket(socket);
		// BluetoothSocket socket=app.getSocket();
		if (socket == null) {
			LogUtils.i(TAG, "Socket is null,can not connect!");
			return;
		}
		try {
			// if (socket.isConnected()) {
			// LogUtils.i(TAG, "Socket is connected do not connection again!");
			// } else {
			socket.connect();
			// }
		} catch (IOException e) {
			LogUtils.i(TAG, "Connect socket throws exception!");
			// msg.what=0;
			e.printStackTrace();
			// handler.sendMessage(msg);
		}
		if (socket.isConnected()) {
			Log.i(TAG, "Socket connected!");
			try {
				app.setInputStream(socket.getInputStream());
				Log.i(TAG, "SetInputStream:" + app.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				app.setOutputStream(socket.getOutputStream());
				Log.i(TAG, "SetOutputStream:" + app.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			LogUtils.i(TAG, "SetSendMessage!");
			app.setSendMsg(new SendMessage(app));

			// msg.what=1;
		} else {
			LogUtils.i(TAG, "Socket is not connected!");
			// msg.what=0;
		}
		// handler.sendMessage(msg);
		LogUtils.i(TAG, "ThreadEnd!");
	}

	private BluetoothDevice getBluetoothDevice() {
		BluetoothDevice device = null;
		if (adapter == null) {
			LogUtils.i(TAG, "adapter is null can not get blue tooth device!");
			return null;
		}
		try {
			LogUtils.i(TAG, "Begin getBluetoothDevice!");
			device = adapter.getBondedDevices().iterator().next();
			LogUtils.i(TAG, "End getBluetoothDevice!Add:" + device.getAddress()
					+ "Name:" + device.getName() + "UUIDs:" + device.getUuids());
			for (ParcelUuid p : device.getUuids()) {
				LogUtils.i(TAG, "P:" + p.toString());
				LogUtils.i(TAG, "UUID:" + p.getUuid().toString());
			}
		} catch (NoSuchElementException e) {
			LogUtils.e(TAG, "BluetoothMayNotOpen!");
			e.printStackTrace();
		}
		return device;
	}

	private BluetoothSocket createBluetoothSocket(BluetoothDevice device) {
		if (device == null) {
			LogUtils.i(TAG, "Device is null can not create socket!");
			return null;
		}
		BluetoothSocket socket = null;
		try {
			LogUtils.i(TAG,
					"Use UUID to create socket at createBluetoothSocket(BluetoothDevice device)");
			// adapter.listenUsingInsecureRfcommWithServiceRecord(name, id);
			// return device.createRfcommSocketToServiceRecord(id);
			socket = device.createInsecureRfcommSocketToServiceRecord(id);
			LogUtils.i(TAG, "Use UUID to create socket successful!");
			LogUtils.i(TAG, "Socket:" + socket.toString());
			return socket;
		} catch (IOException e) {
			LogUtils.e(TAG,
					"Throws exception at createBluetoothSocket(BluetoothDevice device)");
			e.printStackTrace();
			return null;
		}
	}

	private BluetoothSocket createBluetoothSocket1(BluetoothDevice device) {
		Method m = null;
		try {
			m = device.getClass().getMethod("createRfcommSocket",
					new Class[] { int.class });
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		try {
			socket = (BluetoothSocket) m.invoke(device, Integer.valueOf(2));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return socket;
	}
}
